<template>
  <div class="reception-checkin">
    <div class="header">
      <h2>入住登记</h2>
      <p>为线下办理入住的老人和家属进行入住登记</p>
    </div>

    <!-- 入住登记表单 -->
    <el-card class="checkin-form-card">
      <template #header>
        <div class="card-header">
          <span>入住登记信息</span>
          <el-button type="primary" @click="showCheckinDialog = true">
            <el-icon><Plus /></el-icon>
            办理入住
          </el-button>
        </div>
      </template>

      <!-- 入住记录列表 -->
      <el-table :data="checkinRecords" v-loading="loading">
        <el-table-column prop="elderName" label="老人姓名" width="120" />
        <el-table-column prop="elderId" label="老人ID" width="100" />
        <el-table-column prop="bedId" label="床位ID" width="100" />
        <el-table-column prop="caregiverName" label="负责护工" width="120" />
        <el-table-column prop="caregiverPhone" label="护工电话" width="120" />
        <el-table-column prop="familyPhone" label="家属电话" width="120" />
        <el-table-column prop="checkinDate" label="入住日期" width="120" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === '入住中' ? 'success' : 'info'">
              {{ row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120">
          <template #default="{ row }">
            <el-button type="primary" link @click="viewCheckinDetail(row)">
              查看详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 入住登记对话框 -->
    <el-dialog
      v-model="showCheckinDialog"
      title="办理入住登记"
      width="800px"
      :before-close="handleClose"
    >
      <el-form
        ref="checkinFormRef"
        :model="checkinForm"
        :rules="checkinRules"
        label-width="120px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="老人姓名" prop="elderName">
              <el-input v-model="checkinForm.elderName" placeholder="请输入老人姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="老人年龄" prop="age">
              <el-input-number
                v-model="checkinForm.age"
                :min="60"
                :max="120"
                placeholder="请输入年龄"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="性别" prop="gender">
              <el-radio-group v-model="checkinForm.gender">
                <el-radio label="男">男</el-radio>
                <el-radio label="女">女</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="健康状况" prop="healthStatus">
              <el-select v-model="checkinForm.healthStatus" placeholder="请选择健康状况">
                <el-option label="良好" value="良好" />
                <el-option label="一般" value="一般" />
                <el-option label="较差" value="较差" />
                <el-option label="需要特别照护" value="需要特别照护" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="checkinForm.phone" placeholder="请输入老人联系电话" />
        </el-form-item>

        <el-form-item label="家庭地址" prop="address">
          <el-input
            v-model="checkinForm.address"
            type="textarea"
            :rows="2"
            placeholder="请输入家庭地址"
          />
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="身份证类型" prop="idType">
              <el-select v-model="checkinForm.idType" placeholder="请选择身份证类型">
                <el-option label="身份证" value="身份证" />
                <el-option label="护照" value="护照" />
                <el-option label="其他" value="其他" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="身份证号" prop="idNumber">
              <el-input v-model="checkinForm.idNumber" placeholder="请输入身份证号" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="分配床位" prop="bedId">
          <el-select v-model="checkinForm.bedId" placeholder="请选择床位" @change="handleBedChange">
            <el-option
              v-for="bed in availableBeds"
              :key="bed.bedId"
              :label="`${bed.roomNumber}-${bed.bedNumber} (${bed.status})`"
              :value="bed.bedId"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="分配护工" prop="caregiverId">
          <el-select v-model="checkinForm.caregiverId" placeholder="请选择护工">
            <el-option
              v-for="caregiver in availableCaregivers"
              :key="caregiver.caregiverId"
              :label="`${caregiver.name} (${caregiver.phone}) - 已负责${caregiver.currentElders}人`"
              :value="caregiver.caregiverId"
            />
          </el-select>
        </el-form-item>

        <!-- 家属信息 -->
        <el-divider>家属信息</el-divider>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="家属姓名" prop="familyName">
              <el-input v-model="checkinForm.familyName" placeholder="请输入家属姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="家属电话" prop="familyPhone">
              <el-input v-model="checkinForm.familyPhone" placeholder="请输入家属电话" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="与老人关系" prop="relationship">
          <el-select v-model="checkinForm.relationship" placeholder="请选择关系">
            <el-option label="子女" value="子女" />
            <el-option label="配偶" value="配偶" />
            <el-option label="兄弟姐妹" value="兄弟姐妹" />
            <el-option label="其他亲属" value="其他亲属" />
          </el-select>
        </el-form-item>

        <el-form-item label="紧急联系人" prop="emergencyContact">
          <el-input v-model="checkinForm.emergencyContact" placeholder="请输入紧急联系人" />
        </el-form-item>

        <el-form-item label="紧急联系电话" prop="emergencyPhone">
          <el-input v-model="checkinForm.emergencyPhone" placeholder="请输入紧急联系电话" />
        </el-form-item>

        <!-- 协议签订 -->
        <el-divider>入院协议</el-divider>
        
        <el-form-item label="签订协议" prop="agreementSigned">
          <el-switch
            v-model="checkinForm.agreementSigned"
            active-text="已签订"
            inactive-text="未签订"
          />
        </el-form-item>

        <el-form-item label="协议内容" prop="agreementContent" v-if="checkinForm.agreementSigned">
          <el-input
            v-model="checkinForm.agreementContent"
            type="textarea"
            :rows="4"
            placeholder="请输入协议内容或上传协议文件"
          />
        </el-form-item>

        <el-form-item label="自动创建家属账号" prop="autoCreateFamilyAccount">
          <el-switch
            v-model="checkinForm.autoCreateFamilyAccount"
            active-text="自动创建"
            inactive-text="手动创建"
          />
        </el-form-item>

        <el-form-item
          label="家属登录账号"
          prop="familyUsername"
          v-if="checkinForm.autoCreateFamilyAccount"
        >
          <el-input v-model="checkinForm.familyUsername" placeholder="请输入家属登录账号" />
        </el-form-item>

        <el-form-item
          label="家属登录密码"
          prop="familyPassword"
          v-if="checkinForm.autoCreateFamilyAccount"
        >
          <el-input
            v-model="checkinForm.familyPassword"
            type="password"
            placeholder="请输入家属登录密码"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showCheckinDialog = false">取消</el-button>
          <el-button type="primary" @click="submitCheckin" :loading="submitting">
            提交入住登记
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 入住详情对话框 -->
    <el-dialog
      v-model="showDetailDialog"
      title="入住详情"
      width="600px"
    >
      <el-descriptions :column="2" border v-if="currentRecord">
        <el-descriptions-item label="老人姓名">{{ currentRecord.elderName }}</el-descriptions-item>
        <el-descriptions-item label="老人ID">{{ currentRecord.elderId }}</el-descriptions-item>
        <el-descriptions-item label="床位ID">{{ currentRecord.bedId }}</el-descriptions-item>
        <el-descriptions-item label="负责护工">{{ currentRecord.caregiverName }}</el-descriptions-item>
        <el-descriptions-item label="护工电话">{{ currentRecord.caregiverPhone }}</el-descriptions-item>
        <el-descriptions-item label="家属电话">{{ currentRecord.familyPhone }}</el-descriptions-item>
        <el-descriptions-item label="入住日期">{{ currentRecord.checkinDate }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="currentRecord.status === '入住中' ? 'success' : 'info'">
            {{ currentRecord.status }}
          </el-tag>
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { getCheckinRecords, submitCheckinRecord, getAvailableBeds, getAvailableCaregivers } from '@/api/checkin'

// 响应式数据
const loading = ref(false)
const submitting = ref(false)
const showCheckinDialog = ref(false)
const showDetailDialog = ref(false)
const checkinFormRef = ref()
const currentRecord = ref(null)

// 分页数据
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 入住记录列表
const checkinRecords = ref([])

// 可用床位和护工
const availableBeds = ref([])
const availableCaregivers = ref([])

// 入住表单
const checkinForm = reactive({
  elderName: '',
  age: 60,
  gender: '男',
  healthStatus: '一般',
  phone: '',
  address: '',
  idType: '身份证',
  idNumber: '',
  bedId: '',
  caregiverId: '',
  familyName: '',
  familyPhone: '',
  relationship: '子女',
  emergencyContact: '',
  emergencyPhone: '',
  agreementSigned: false,
  agreementContent: '',
  autoCreateFamilyAccount: true,
  familyUsername: '',
  familyPassword: '123456'
})

// 表单验证规则
const checkinRules = {
  elderName: [{ required: true, message: '请输入老人姓名', trigger: 'blur' }],
  age: [{ required: true, message: '请输入年龄', trigger: 'blur' }],
  gender: [{ required: true, message: '请选择性别', trigger: 'change' }],
  phone: [{ required: true, message: '请输入联系电话', trigger: 'blur' }],
  bedId: [{ required: true, message: '请选择床位', trigger: 'change' }],
  caregiverId: [{ required: true, message: '请选择护工', trigger: 'change' }],
  familyName: [{ required: true, message: '请输入家属姓名', trigger: 'blur' }],
  familyPhone: [{ required: true, message: '请输入家属电话', trigger: 'blur' }]
}

// 加载入住记录
const loadCheckinRecords = async () => {
  loading.value = true
  try {
    const response = await getCheckinRecords({
      page: currentPage.value,
      size: pageSize.value
    })
    checkinRecords.value = response.data.records || []
    total.value = response.data.total || 0
  } catch (error) {
    ElMessage.error('加载入住记录失败：' + error.message)
  } finally {
    loading.value = false
  }
}

// 加载可用资源
const loadAvailableResources = async () => {
  try {
    const [bedsResponse, caregiversResponse] = await Promise.all([
      getAvailableBeds(),
      getAvailableCaregivers()
    ])
    availableBeds.value = bedsResponse.data || []
    availableCaregivers.value = caregiversResponse.data || []
  } catch (error) {
    ElMessage.error('加载资源失败：' + error.message)
  }
}

// 提交入住登记
const submitCheckin = async () => {
  if (!checkinFormRef.value) return
  
  try {
    await checkinFormRef.value.validate()
    submitting.value = true
    
    await submitCheckinRecord(checkinForm)
    ElMessage.success('入住登记成功')
    showCheckinDialog.value = false
    loadCheckinRecords()
    resetCheckinForm()
  } catch (error) {
    if (error.errors) {
      ElMessage.error('请完善表单信息')
    } else {
      ElMessage.error('入住登记失败：' + error.message)
    }
  } finally {
    submitting.value = false
  }
}

// 查看入住详情
const viewCheckinDetail = (record) => {
  currentRecord.value = record
  showDetailDialog.value = true
}

// 重置表单
const resetCheckinForm = () => {
  Object.assign(checkinForm, {
    elderName: '',
    age: 60,
    gender: '男',
    healthStatus: '一般',
    phone: '',
    address: '',
    idType: '身份证',
    idNumber: '',
    bedId: '',
    caregiverId: '',
    familyName: '',
    familyPhone: '',
    relationship: '子女',
    emergencyContact: '',
    emergencyPhone: '',
    agreementSigned: false,
    agreementContent: '',
    autoCreateFamilyAccount: true,
    familyUsername: '',
    familyPassword: '123456'
  })
}

// 床位选择变化
const handleBedChange = (bedId) => {
  const selectedBed = availableBeds.value.find(bed => bed.bedId === bedId)
  if (selectedBed) {
    ElMessage.info(`已选择床位：${selectedBed.roomNumber}-${selectedBed.bedNumber}`)
  }
}

// 分页处理
const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
  loadCheckinRecords()
}

const handleCurrentChange = (page) => {
  currentPage.value = page
  loadCheckinRecords()
}

// 对话框关闭处理
const handleClose = (done) => {
  ElMessageBox.confirm('确定要关闭吗？未保存的数据将丢失。')
    .then(() => {
      resetCheckinForm()
      done()
    })
    .catch(() => {
      // 取消关闭
    })
}

// 生命周期
onMounted(() => {
  loadCheckinRecords()
  loadAvailableResources()
})
</script>

<style scoped>
.reception-checkin {
  padding: 20px;
}

.header {
  margin-bottom: 20px;
}

.header h2 {
  margin: 0;
  color: #303133;
}

.header p {
  margin: 5px 0 0 0;
  color: #909399;
  font-size: 14px;
}

.checkin-form-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>
